// src/router.js
const express = require('express')
//给req增加一个cookies属性
const cookieParser = require('cookie-parser')
//给req增加一个body属性
const bodyParser = require('body-parser');
//增加可以跨域的模块
const cors = require('cors');
//文件写入和读取用
const fs = require('fs')
const router = express.Router()
router.use(bodyParser.urlencoded({ extended: false }))
router.use(cookieParser());
router.use(cors({
  origin: [
    'http://47.98.138.5:8080',
    'http://47.98.138.5:8081',
    'http://47.98.138.5:8082',
    'http://47.98.138.5:8083',
    'http://47.98.138.5:8084',
    'http://47.98.138.5:8085',
    'http://47.98.138.5:8086',
    'http://47.98.138.5:8087',
    'http://47.98.138.5:8088',
    'http://47.98.138.5:8089'
  ],
  credentials: true
}));

//user路由
// router.get('/user',(req,res)=>{
//   // res.header('Access-Control-Allow-Origin','http://127.0.0.1:8080');
//   // res.header('Access-Control-Allow-Credentials',true);
//   res.send(req.cookies);
// });

//user路由
router.get('/user', (req, res) => {
  res.header('Access-Control-Allow-Origin', 'http://47.98.138.5:8087');
  let id = req.query.id;
  res.sendFile(`${__dirname}/homework/${id}.json`)
});

router.post('/user', (req, res) => {
  let data = req.body.changeStr;
  fs.writeFile(`${__dirname}/homework/s1.json`, data, () => {
    res.send('change successfully~!')
  });
});
//接口，用来把router传递出去
module.exports = router;